package com.lancoo.klgcourseware.ui.fragment.klgSubjectFragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Environment;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.lancoo.klgcourseware.R;
import com.lancoo.klgcourseware.base.BaseKlgPresenter;
import com.lancoo.klgcourseware.entity.bean.ErrorStates;
import com.lancoo.klgcourseware.entity.bean.KlgCommonBean;
import com.lancoo.klgcourseware.entity.bean.KlgDbConstant;
import com.lancoo.klgcourseware.manager.KlgMediaManager;
import com.lancoo.klgcourseware.presenter.KnowledgeEnglishPresenter;
import com.lancoo.klgcourseware.ui.activity.KlgBasicTrainActivity;
import com.lancoo.klgcourseware.ui.activity.KlgImageViewPagerActivity;
import com.lancoo.klgcourseware.ui.widget.CustomNestedScrollView;
import com.lancoo.klgcourseware.ui.widget.VolumeAlignImageSpan;
import com.lancoo.klgcourseware.utils.KlgBitmapUtils;
import com.lancoo.klgcourseware.utils.KlgToolUtils;
import com.lancoo.klgcourseware.utils.klog.KLog;
import com.lancoo.klgcourseware.view.IKnowledgeEnglishView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import lancoo.com.net.retrofitrxjava.RxApiManager;
import lancoo.com.net.retrofitrxjava.download.FileDownLoadObserver;
import lancoo.com.net.retrofitrxjava.download.HttpDownManager;

/**
 * Created by pengmi on 2019/8/14 15:18
 * Description:英语学科知识点课件卡片分页
 */
public class KnowledgeEnglishFragment extends SubjectKnowledgeFragment implements IKnowledgeEnglishView {


    private KnowledgeEnglishPresenter mPresenter;
    private ImageView img_usPhonetic,img_unPhonetic,img_senPhonetic;
    private KlgMediaManager klgMediaManager;
    private KlgCommonBean klgCommonBean;
    private RelativeLayout ll_sentenceStructures;
    private LinearLayout ll_usPhonetic,ll_unPhonetic;
    private TextView tv_sentenceStructures;
    private VolumeAlignImageSpan centerAlignImageSpan;

    @Override
    protected int getContentViewId() {
        return R.layout.klg_fragment_english_courseware;
    }

    @Override
    protected void initView(View view) {

        mPresenter = new KnowledgeEnglishPresenter(getContext(),this);
        if(!getArguments().getBoolean("hideLoading")){
            mPresenter.requestInfo(klgCode);
        }else{
            mPresenter.getWordCode(klgCode);
        }

    }


    @Override
    public void loadingSuccess(KlgCommonBean klgCommonBean, BaseKlgPresenter.LoadStatus status) {
        KLog.json(new Gson().toJson(klgCommonBean));
        if(klgCommonBean==null){
            dismissLoadingLayout();
            showEmptyLayout();
        }else{
            initData(klgCommonBean);
            if(loadDataSuccess!=null){
                loadDataSuccess.onLoadSuccess();
            }
            if(!expandTrain){
                return;
            }
            if(!TextUtils.isEmpty(klgCommonBean.getUs_voice())){
                playSound(klgCommonBean.getUs_voice(),img_usPhonetic);
            }else if(!TextUtils.isEmpty(klgCommonBean.getUn_voice())){
                playSound(klgCommonBean.getUn_voice(),img_unPhonetic);
            }else if(!TextUtils.isEmpty(klgCommonBean.getClassicVoice())){
                if(TextUtils.equals(klgCommonBean.getKlgType(),"F")){
                    showSign();
                }else{
                    playSound(klgCommonBean.getClassicVoice(),img_senPhonetic);
                }
            }else {
                if(expandTrain){

                }
            }
            if (Build.VERSION.SDK_INT >= 23) {
                verifyPermissions(getActivity());
                //  Log.e("6.0以上的版本---->", "获取权限");
            }
            if(getContext()!=null){
                SharedPreferences sp = getContext().getSharedPreferences("lancoo_freeStudy_sp", Context.MODE_PRIVATE);
                if(sp.getInt("currentUserType",2)!=2){
                    convertView.findViewById(R.id.rl_bottom).setVisibility(View.GONE);
                    expandTrain=false;
                }
            }
        }


    }

    @Override
    public void showLoadingPg() {
        showLoadingProgress();
    }

    @Override
    public void loadingFailure(ErrorStates errorStates) {
        showFailureLoad(errorStates);
        if(loadDataSuccess!=null){
            loadDataSuccess.onLoadFailure();
        }
    }

    /**
     * 使用klgCommonBean公共模型加载数据
     * @param klgCommonBean
     */
    private void initData(final KlgCommonBean klgCommonBean){
        this.klgCommonBean = klgCommonBean;
        ViewStub viewStub = convertView.findViewById(R.id.viewstub_main_data);
        if(viewStub!=null){
            viewStub.inflate();
            setTitleName(klgCommonBean.getKlgName());
            //知识点内容
            final TextView tv_klgName = convertView.findViewById(R.id.tv_klg_name);
            tv_klgName.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    int lineCount = tv_klgName.getLayout().getLineCount();
                    int textSize=KlgToolUtils.px2sp(getContext(),tv_klgName.getTextSize());
                    Log.e("eeeeee",lineCount+"...textSize:"+textSize);
                    if(KlgToolUtils.isPad(getContext())){
                        if(textSize==45){
                            if(lineCount>1){
                                tv_klgName.setTextSize(40);
                                tv_klgName.setLineSpacing(10,1f);
                                return;
                            }
                        }else if(textSize==40){
                            if(lineCount>2){
                                tv_klgName.setTextSize(35);
                                tv_klgName.setLineSpacing(20,1f);
                                return;
                            }
                        }
                    }else{
                        if(textSize==36){
                            if(lineCount>1){
                                tv_klgName.setTextSize(30);
                                tv_klgName.setLineSpacing(10,1f);
                                return;
                            }
                        }else if(textSize==30){
                            if(lineCount>2){
                                tv_klgName.setTextSize(24);
                                tv_klgName.setLineSpacing(20,1f);
                                return;
                            }
                        }
                    }

                    dismissLoadingLayout();
                    tv_klgName.getViewTreeObserver().removeOnGlobalLayoutListener(this);

                    Log.e("aaaa","文字绘制完毕，共"+lineCount+"行");
                    StringBuilder stringBuilder=new StringBuilder();
                    for (int i = 0; i < lineCount; i++) {
                        int lineStart = tv_klgName.getLayout().getLineStart(i);
                        int lineEnd=tv_klgName.getLayout().getLineEnd(i);
                        Log.e("aaaa","第"+i+"行"+",start:"+lineStart+"...end:"+lineEnd);
                        if(lineStart>0){
                            char b=tv_klgName.getText().toString().charAt(lineStart );
                            char a = tv_klgName.getText().toString().charAt(lineStart - 1);
                            if(a>='A'&&a<='Z'||a>='a'&&a<='z'){
                                Log.e("aaaaa","需要增加-");
                                stringBuilder.append(" -");
                            }else{
                                Log.e("aaaaa","不需要增加-");
                            }
                            Log.e("aaaa","a:"+a+"...b:"+b);
                        }
                        stringBuilder.append(tv_klgName.getText().toString().substring(lineStart,lineEnd));
                    }
                    tv_klgName.setText(stringBuilder.toString());
                }
            });
            tv_klgName.setText(klgCommonBean.getKlgName());
            tv_klgName.setMovementMethod(ScrollingMovementMethod.getInstance());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                tv_klgName.setLetterSpacing(0.04f);
            }
            //音频播放动画
            img_usPhonetic = convertView.findViewById(R.id.img_us_phonetic);
            img_unPhonetic = convertView.findViewById(R.id.img_un_phonetic);
            img_senPhonetic = convertView.findViewById(R.id.img_sentence_strutures);
            img_senPhonetic.setVisibility(View.GONE);
            controlImgAnimation(false,false,false);
            convertView.findViewById(R.id.tv_basic_train).setOnClickListener(this);
            //知识点发音
            if(TextUtils.isEmpty(klgCommonBean.getUn_phonetic())&&TextUtils.isEmpty(klgCommonBean.getUs_phonetic())&&TextUtils.isEmpty(klgCommonBean.getUn_voice())&&TextUtils.isEmpty(klgCommonBean.getUs_voice())){
                convertView.findViewById(R.id.ll_fayin).setVisibility(View.GONE);
            }else{
                if(TextUtils.isEmpty(klgCommonBean.getUn_phonetic())&&TextUtils.isEmpty(klgCommonBean.getUn_voice())){
                    convertView.findViewById(R.id.ll_un_phonetic).setVisibility(View.GONE);
                }else{
                    TextView tv_unPhonetic = convertView.findViewById(R.id.tv_un_phonetic);
                    if(TextUtils.isEmpty(klgCommonBean.getUn_phonetic())){
                        tv_unPhonetic.setText(getContext().getString(R.string.klg_un));
                    }else{
                        tv_unPhonetic.setText(getContext().getString(R.string.klg_un)+" "+ klgCommonBean.getUn_phonetic());
                    }
                    if(!TextUtils.isEmpty(klgCommonBean.getUn_voice())){
                        ll_unPhonetic = convertView.findViewById(R.id.ll_un_phonetic);
                        ll_unPhonetic.setTag(klgCommonBean.getUn_voice());
                        ll_unPhonetic.setOnClickListener(this);
                    }
                    try{
                        Typeface typeFace = Typeface.createFromAsset(getContext().getAssets(), "klg_droid_sans_bold.ttf");
                        tv_unPhonetic.setTypeface(typeFace);
                    }catch (Exception e){

                    }
                }
                if(TextUtils.isEmpty(klgCommonBean.getUs_phonetic())&&TextUtils.isEmpty(klgCommonBean.getUs_voice())){
                    convertView.findViewById(R.id.ll_us_phonetic).setVisibility(View.GONE);
                }else{
                    TextView tv_usPhonetic = convertView.findViewById(R.id.tv_us_phonetic);
                    if(TextUtils.isEmpty(klgCommonBean.getUs_phonetic())){

                        tv_usPhonetic.setText(getContext().getString(R.string.klg_us));
//                        convertView.findViewById(R.id.tv_us_phonetic).setVisibility(View.GONE);
                    }else{
                        tv_usPhonetic.setText(getContext().getString(R.string.klg_us)+" "+ klgCommonBean.getUs_phonetic());
                    }
                    if(!TextUtils.isEmpty(klgCommonBean.getUs_voice())){
                        ll_usPhonetic = convertView.findViewById(R.id.ll_us_phonetic);
                        ll_usPhonetic.setTag(klgCommonBean.getUs_voice());
                        ll_usPhonetic.setOnClickListener(this);
                    }
                    try{
                        Typeface typeFace = Typeface.createFromAsset(getContext().getAssets(), "klg_droid_sans_bold.ttf");
                        tv_usPhonetic.setTypeface(typeFace);
                    }catch (Exception e){

                    }
                }
                if(convertView.findViewById(R.id.ll_un_phonetic).getVisibility()==View.GONE&&convertView.findViewById(R.id.ll_us_phonetic).getVisibility()==View.VISIBLE){
//                    convertView.findViewById(R.id.us_right_padding).setVisibility(View.VISIBLE);
                }
                if(convertView.findViewById(R.id.ll_us_phonetic).getVisibility()==View.GONE&&convertView.findViewById(R.id.ll_un_phonetic).getVisibility()==View.VISIBLE){
//                    convertView.findViewById(R.id.un_left_padding).setVisibility(View.VISIBLE);
                }
            }
            //知识点释义
            if(TextUtils.isEmpty(klgCommonBean.getExplain())){
                convertView.findViewById(R.id.tv_meaning_explain).setVisibility(View.GONE);
                convertView.findViewById(R.id.tv_meaning).setVisibility(View.GONE);
            }else {
                TextView tv_explain=convertView.findViewById(R.id.tv_meaning);
                if(klgCommonBean.isShowMoreMeaning()&&!TextUtils.isEmpty(klgCommonBean.getShortExplan())){
                    tv_explain.setText(klgCommonBean.getShortExplan());
                    convertView.findViewById(R.id.tv_more).setVisibility(View.VISIBLE);
                    convertView.findViewById(R.id.tv_more).setOnClickListener(this);
                }else {
                    tv_explain.setText(klgCommonBean.getExplain());
                    convertView.findViewById(R.id.tv_more).setVisibility(View.GONE);
                }



            }
            //句型
            if(TextUtils.isEmpty(klgCommonBean.getParaphrase())){
                convertView.findViewById(R.id.tv_sentence_pattern_explain).setVisibility(View.GONE);
                convertView.findViewById(R.id.tv_sentence_pattern).setVisibility(View.GONE);
            }else{
                TextView tv_sentence = convertView.findViewById(R.id.tv_sentence_pattern);
                tv_sentence.setText(klgCommonBean.getParaphrase());
            }
            //用法
            if(TextUtils.isEmpty(klgCommonBean.getUsage())){
                convertView.findViewById(R.id.tv_usage_analysis_explain).setVisibility(View.GONE);
                convertView.findViewById(R.id.tv_usage_analysis).setVisibility(View.GONE);
            }else{
                TextView tv_usageAnalysis = convertView.findViewById(R.id.tv_usage_analysis);
                tv_usageAnalysis.setText(klgCommonBean.getUsage());
            }
            //例句
            if(TextUtils.isEmpty(klgCommonBean.getClassicSen())){
                convertView.findViewById(R.id.tv_sentence_structures_explain).setVisibility(View.GONE);
                convertView.findViewById(R.id.ll_sentence_structures).setVisibility(View.GONE);
            }else{
                tv_sentenceStructures = convertView.findViewById(R.id.tv_sentence_structures);
                TextView tv_sentenceStructureChinese = convertView.findViewById(R.id.tv_sentence_structures_chinese);
//                tv_sentenceStructures.setText(Html.fromHtml(klgCommonBean.getClassicSen()));
                tv_sentenceStructureChinese.setText(klgCommonBean.getClassicTrain());
                SpannableStringBuilder spannableStringBuilder=new SpannableStringBuilder();
                SpannableString ss_content=new SpannableString(Html.fromHtml(klgCommonBean.getClassicSen().replace("font color='#0077f0'","font color='#64a9d0'")));
                spannableStringBuilder.append(ss_content);
                if(!TextUtils.isEmpty(klgCommonBean.getClassicVoice())){
                    ll_sentenceStructures = convertView.findViewById(R.id.ll_sentence_structures);
                    ll_sentenceStructures.setTag(klgCommonBean.getClassicVoice());
                    ll_sentenceStructures.setOnClickListener(this);
                    String imgSpanStr="  lpl";
                    SpannableString ss_volume=new SpannableString(imgSpanStr);
                    Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.klg_volume_cyan_4);
                    if(centerAlignImageSpan==null){
                        centerAlignImageSpan = new VolumeAlignImageSpan(getContext(),bitmap);
                    }else{
                        centerAlignImageSpan.destoryVolumeImageSpan(tv_sentenceStructures);
                    }
                    ss_volume.setSpan(centerAlignImageSpan,imgSpanStr.length()-3,imgSpanStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableStringBuilder.append(ss_volume);
                    SpannableString ss_end=new SpannableString("1");
                    ss_end.setSpan(new ForegroundColorSpan(Color.TRANSPARENT),0,1,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableStringBuilder.append(ss_end);
                }
                tv_sentenceStructures.setText(spannableStringBuilder);
            }
            CustomNestedScrollView scrollView = convertView.findViewById(R.id.scroll_view);
            if(onScrollListener!=null){
                scrollView.setOnScrollListener(onScrollListener);
            }
        }
        downloadPhonetic(getContext(),klgCommonBean.getUs_voice(),0);
        downloadPhonetic(getContext(),klgCommonBean.getUn_voice(),1);

        if(TextUtils.equals("ESP",klgCommonBean.getKlgType())){
//            convertView.findViewById(R.id.rl_bottom).setVisibility(mPresenter.isEnableExpandTrain()?View.VISIBLE:View.GONE);
            convertView.findViewById(R.id.tv_sentence_structures_explain).setVisibility(View.GONE);
            convertView.findViewById(R.id.ll_sentence_structures).setVisibility(View.GONE);
            enableShowSign=false;
            if(!TextUtils.isEmpty(klgCommonBean.getClassicSen())){
                ViewStub stub = convertView.findViewById(R.id.viewstub_train_picture);
                if(stub!=null){
                    stub.inflate();
                    final ImageView img_picture=convertView.findViewById(R.id.img_picture);
//                    Glide.with(getContext()).load(KlgDbConstant.mediaUrl+klgCommonBean.getClassicSen()).into(img_picture);
                    Glide.with(getContext()).asBitmap().load(KlgDbConstant.mediaUrl+klgCommonBean.getClassicSen())
                            .into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL,Target.SIZE_ORIGINAL) {
                                @Override
                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                    int width = resource.getWidth();//图片原始宽度
                                    int height = resource.getHeight();//图片原始高度
                                    int scaledW = KlgToolUtils.getWidthInPx(getContext())-KlgToolUtils.dip2px(getContext(),KlgToolUtils.isPad(getContext())?120f:70f);//固定图片展示高度为180dp
                                    int scaledH = (height * scaledW) /width ;//计算出按比缩放后的宽度
//                                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(scaledW, scaledH);
//                                    img_picture.setLayoutParams(lp);
                                    String format =klgCommonBean.getClassicSen().substring(klgCommonBean.getClassicSen().lastIndexOf(".")+1);
                                    if(TextUtils.equals(format.toLowerCase(),"png")){
                                        img_picture.setImageBitmap(Bitmap.createScaledBitmap(resource, scaledW, scaledH, true));
                                    }else{
                                        img_picture.setImageBitmap(KlgBitmapUtils.zoomImage(resource,scaledW,scaledH));
                                    }


                                }
                            });
                    img_picture.setOnClickListener(this);
                }
            }
            Log.e("eeeeeeee","ESP不可以进入基础训练"+expandTrain);
            if(!mPresenter.isEnableExpandTrain()){//不可以进入基础训练
                TextView tv_basicTrain = convertView.findViewById(R.id.tv_basic_train);
                Log.e("eeeeeeee","不可以进入基础训练");
                tv_basicTrain.setBackgroundResource(R.drawable.klg_shape_bottom_btn_gray_bg);
                tv_basicTrain.setOnClickListener(null);
                convertView.findViewById(R.id.shadow_basic_train).setBackgroundResource(R.drawable.klg_icon_shadow_gray);
                enableShowSign=false;
            }
            if(!expandTrain){
                convertView.findViewById(R.id.rl_bottom).setVisibility(View.GONE);
            }
            return;
        }
        downloadPhonetic(getContext(),klgCommonBean.getClassicVoice(),2);
        if(!expandTrain){
            Log.e("eeeeeeee","不可以进入基础训练"+expandTrain);
            convertView.findViewById(R.id.rl_bottom).setVisibility(View.GONE);
            return;
        }
        if(!mPresenter.isEnableExpandTrain()){//不可以进入基础训练
            TextView tv_basicTrain = convertView.findViewById(R.id.tv_basic_train);
            Log.e("eeeeeeee","不可以进入基础训练");
            tv_basicTrain.setBackgroundResource(R.drawable.klg_shape_bottom_btn_gray_bg);
            tv_basicTrain.setOnClickListener(null);
            convertView.findViewById(R.id.shadow_basic_train).setBackgroundResource(R.drawable.klg_icon_shadow_gray);
            enableShowSign=false;
        }
        Log.e("aaaa",klgCommonBean.getKlgType());
    }

    protected void showEmptyLayout(){
        ViewStub stub = convertView.findViewById(R.id.viewstub_empty);
        if(stub!=null){
            stub.inflate();
        }

    }


    @Override
    public void onClick(View v) {
        if(System.currentTimeMillis()-time<500){
            return;
        }
        time=System.currentTimeMillis();
        super.onClick(v);
        int id=v.getId();
        if(id==R.id.ll_sentence_structures){//例句
            String url = (String) v.getTag();
            playSound(url,img_senPhonetic);
        }else if(id==R.id.ll_us_phonetic){//美式
            String url = (String) v.getTag();
            playSound(url,img_usPhonetic);
        }else if(id==R.id.ll_un_phonetic){//英式
            String url = (String) v.getTag();
            playSound(url,img_unPhonetic);
        }else if(id==R.id.tv_basic_train){
            if(verifyPermissions(getActivity())){
                enableShowSign=false;
//                KlgMoreActivity.launch(getActivity(),"",klgCommonBean);
                KlgBasicTrainActivity.launch(getActivity(),klgCommonBean);
//                KlgIntermediateBasicTrainActivity.launch(getActivity(),klgCommonBean);
            }
        }else if(id==R.id.img_picture){
            String url = KlgDbConstant.mediaUrl+klgCommonBean.getClassicSen();
            List<String> urlList=new ArrayList<>();
            urlList.add(url);
            KlgImageViewPagerActivity.launch(getContext(),urlList,0);
        }else if(id==R.id.tv_more){
            v.setVisibility(View.GONE);
            TextView textView = convertView.findViewById(R.id.tv_meaning);
            if(textView!=null){
                textView.setText(klgCommonBean.getExplain());
            }
        }
    }

    /**
     * 开启音频播放
     * @param url 音频url
     * @param img imgView
     */
    private void playSound(String url,final ImageView img){
        if(klgMediaManager==null){
            klgMediaManager = new KlgMediaManager(getContext());
        }
        controlImgAnimation(false,false,false);
        klgMediaManager.setUpMedia(url, new KlgMediaManager.OnPlayListener() {

            @Override
            public void onComplete() {
                controlImgAnimation(false,false,false);
                if(expandTrain){
                    showSign();
                }
            }

            @Override
            public void onStartError() {
                controlImgAnimation(false,false,false);
            }

            @Override
            public void onPausePlay() {

            }

            @Override
            public void onSourceError() {
                controlImgAnimation(false,false,false);
            }

            @Override
            public void onResumePlay() {

            }

            @Override
            public void onStopPlay() {

            }

            @Override
            public void onPrepare() {
                if(klgMediaManager!=null){
                    klgMediaManager.start();
                }
                controlImgAnimation(img==img_usPhonetic,img==img_unPhonetic,img==img_senPhonetic);
            }

            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {

            }
        });
    }

    /**
     * 设置动画
     * @param img
     * @param isAnimation
     */
    protected void volumeAnimationControl(ImageView img, boolean isAnimation){
        if(img!=null&&img.getVisibility()== View.VISIBLE){
            if(isAnimation){
//                img.setImageResource(R.drawable.lgklg_animation_list_volume_cyan);
                img.setBackground(null);
                ((AnimationDrawable)img.getDrawable()).start();
            }else{
//                img.setImageResource(R.drawable.lgklg_volume_cyan_3);
                img.setBackgroundResource(R.drawable.klg_volume_cyan_3);
                ((AnimationDrawable)img.getDrawable()).stop();
                ((AnimationDrawable)img.getDrawable()).selectDrawable(0);

            }
        }
    }

    /**
     * 控制美式，英式，例句播放动画
     */
    private void controlImgAnimation(boolean isOpend,boolean isOpen1,boolean isOpend2){
        volumeAnimationControl(img_usPhonetic,isOpend);
        volumeAnimationControl(img_unPhonetic,isOpen1);
        volumeAnimationControl(img_senPhonetic,isOpend2);
        if(centerAlignImageSpan==null){
            return;
        }
        if(isOpend2){
            centerAlignImageSpan.startVolumeAnimation(tv_sentenceStructures);
        }else{
            centerAlignImageSpan.stopVolumeAnimation(tv_sentenceStructures);
        }

    }


    @Override
    public void onPause() {
        super.onPause();
        if(klgMediaManager!=null){
            klgMediaManager.pause();
        }
        controlImgAnimation(false,false,false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(klgMediaManager!=null){
            klgMediaManager.release();
            klgMediaManager=null;
        }
        if(centerAlignImageSpan!=null&&tv_sentenceStructures!=null){
            centerAlignImageSpan.destoryVolumeImageSpan(tv_sentenceStructures);
        }
    }

    @Override
    protected void reloadData() {
        super.reloadData();
        if(mPresenter!=null){
            if(!getArguments().getBoolean("hideLoading")){
                mPresenter.requestInfo(klgCode);
            }else{
                mPresenter.getWordCode(klgCode);
            }
        }
    }

    protected void enterBasicTrain(){
        enableShowSign=false;
        KlgBasicTrainActivity.launch(getActivity(),klgCommonBean);
    }

    private void downloadPhonetic(Context mContext, String url, final int urlType){
        if(TextUtils.isEmpty(url)){
            return;
        }
        Disposable disposable = HttpDownManager.getInstance().downloadFile(url, Environment.getExternalStorageDirectory() +
                "/Android/data/" + mContext.getApplicationInfo().packageName + "/files/record/klgtemp", urlType+""+System.currentTimeMillis()+"."+url.substring(url.lastIndexOf(".") + 1, url.length()), new FileDownLoadObserver<File>() {
            @Override
            public void onDownLoadSuccess(File file) {
//                showTxtContent(file);
                if(urlType==0){
                    if(ll_usPhonetic!=null){
                        ll_usPhonetic.setTag(file.getPath());
                        klgCommonBean.setUs_voice(file.getPath());
                    }
                }else if(urlType==1){
                    if(ll_unPhonetic!=null){
                        ll_unPhonetic.setTag(file.getPath());
                        klgCommonBean.setUn_voice(file.getPath());
                    }
                }else{
                    if(ll_sentenceStructures!=null){
                        ll_sentenceStructures.setTag(file.getPath());
                        klgCommonBean.setClassicVoice(file.getPath());
                    }
                }
            }

            @Override
            public void onDownLoadFail(Throwable throwable) {

            }

            @Override
            public void onProgress(long progress, long total) {

            }
        });
        RxApiManager.getInstance().add(disposable);
    }

    protected void pauseMedia(){
        if(klgMediaManager!=null){
            klgMediaManager.pause();
        }
        controlImgAnimation(false,false,false);
    }

    public void removeConnection(){
        if(mPresenter!=null){
            mPresenter.cancelConnection();
        }
    }

}


